﻿var Utils = {};

Utils.htmlEncode = function(value) {
    if (value) {
        return $('<div />').text(value).html();
    } else {
        return '';
    }
};

Utils.htmlDecode = function(value) {
    if (value) {
        return $('<div />').html(value).text();
    } else {
        return '';
    }
};


//ajax link function: search all link with a fix class name (maybe ajax-link), after that, add function for all found items
//There are also have some specific data for each link: like confirm message, method, show message after success or error...
// VietLH4 - 20 May 2013
Utils.ajaxLink = function () {
    $("a.ajax-link").on('click', function (e) {
        var confirm = $(this).attr('confirm-message');
        var title = $(this).attr('confirm-title');
        var type = $(this).attr('ajax-type');
        var data = $(this).attr('ajax-data');
        var url = $(this).attr('href');
        
        $('<div />')
            .html(confirm)
            .dialog({
                modal: true,
                title: title,
                resizable: false,
                buttons: {
                    "Có": function () {
                        Utils.ajax({
                            type: type,
                            url: url,
                            data: data
                        });
                        $(this).dialog("close");
                    },
                    "Không": function () {
                        $(this).dialog("close");
                    }
                },
                close: function (event, ui) {
                    $(this).remove();
                }
            });

        e.preventDefault();
    });
};

Utils.ajax = function (config) {
    $.ajax({
        type: config.type == undefined ? 'POST' : config.type, //Default: POST
        url: config.url,
        data: config.data == undefined ? null : config.data,
        success: function () {
            //Show saving or success message about 1 or 2 second beside the link
        },
        error: function () {
            //Show error
        },
        beforeSend: function() {
            //show loading on the button link or beside the link
        },
        complete: function () {
            //hide loading on the button link or beside the link
        }
    });
};